<template>
  <ContentWrap>
    <view class="tableOp">
      <el-row type="flex" justify="end">
        <el-button style="" type="primary" @click="showAdd">
          <Icon class="mr-5px" icon="ep:plus" />{{ $t(`global.record`) }}
        </el-button>
      </el-row>
    </view>

    <el-table v-loading="loading" :data="list" :border="true" @row-click="sampleDetails">
      <el-table-column type="index" />
      <el-table-column v-for="(item, index) in checkCol" :key="index" :prop="item.prop" :label="item.label"
        :width="item.width">
        <template #default="scope">
          <view @click.stop v-if="item.prop === 'tags'">
            <view class="flex flex-wrap">
              <view v-for="item1 in scope.row.tags" :key="item1" style="height: 30px;width: max-content;">
                <span class="tableTags">{{ item1 }}</span>
              </view>
            </view>
          </view>
          <view @click.stop style="display:flex;" v-if="item.prop === 'cardScanFilePath'">
            <el-popover placement="top-start" title="Title" :width="200" trigger="hover">
              <el-image :src="scope.row.cardScanFilePath" style="width: 150px;height: 150px" />
              <view style="margin-top: 50px;position: absolute;bottom: 5px;right: 10px">
                <Icon class="mr-5px" icon="ep:download" />
              </view>
              <template #reference>
                <el-image :preview-src-list="[scope.row.cardScanFilePath]" :src="scope.row.cardScanFilePath"
                  style="width: 50px; height: 50px" :z-index="10" />
              </template>
            </el-popover>
          </view>
          <view @click.stop v-if="item.prop === 'list'">
            <view class="flex flex-wrap">
              <el-tag v-for="item1 in scope.row.list" :key="item1" class="tag">
                {{ item1.goods }}
              </el-tag>
            </view>
          </view>
          <view @click.stop v-if="item.prop === 'hislist'">
            <el-text @click="showAccess">
              <!--<Icon class="mr-5px" icon="ep:calendar" />--> {{ scope.row.hislist?.length }}
            </el-text>
          </view>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
                        <span @click.stop>
                          <el-button link type="primary" @click="editDetails(scope.row)">
                            <Icon class="mr-5px" icon="ep:edit" />
                          </el-button>
                        </span>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"
      @pagination="getList" />
    <el-dialog v-model="showsampleDetail" @closed="cacel" class="addDialog" top="8vh" width="80vw">
      <template #header>
        <el-row type="flex" justify="end">
          <el-button type="default" @click="shareLink" >
            <Icon class="mr-5px" icon="ep:share"/>分享
          </el-button>
          <el-button v-if="isEdit" type="danger" @click="deletesample">
            <Icon class="mr-5px" icon="ep:delete" />删除
          </el-button>
        </el-row>
      </template>
      <el-form id="pdfDom" :model="sampleInfo" ref="sampleFormRef" label-position="top"
        style="height: 600px;overflow-y: auto;overflow-x: hidden;">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="样本名称">
              <span v-if="!isEdit && !isAdd">{{ sampleInfo.name }}</span>
              <el-input style="width: 300px" v-model="sampleInfo.name" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接待时间">
              <el-date-picker v-model="sampleInfo.operTime"
                              type="datetime"
                              format="YYYY-MM-DD HH:mm:ss"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              :placeholder="$t(`global.select`)" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="有效期">
              <el-date-picker v-model="sampleInfo.effectiveTime"
                              type="datetime"
                              format="YYYY-MM-DD HH:mm:ss"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              :placeholder="$t(`global.select`)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内部备注">
              <span v-if="!isEdit && !isAdd">{{ sampleInfo.memo }}</span>
              <el-input type="textarea" v-model="sampleInfo.memo" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <span v-if="!isEdit && !isAdd">{{ sampleInfo.internalMemo }}</span>
              <el-input type="textarea" v-model="sampleInfo.internalMemo" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <proList v-model="sampleInfo.list" :readonly="!isAdd && !isEdit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse v-model="activeNames" style="margin-top: 30px">
          <el-collapse-item name="1">
            <template #title>
              <el-text class="form_sub_title">联系方式</el-text>
            </template>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="姓名">
                  <span v-if="!isEdit && !isAdd">{{ sampleInfo.username }}</span>
                  <el-input v-model="sampleInfo.username" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电话">
                  <span v-if="!isEdit && !isAdd">{{ sampleInfo.phone }}</span>
                  <el-input v-model="sampleInfo.phone" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="邮箱">
                  <span v-if="!isEdit && !isAdd">{{ sampleInfo.email }}</span>
                  <el-input v-model="sampleInfo.email" v-else />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="公司地址">
                  <span v-if="!isEdit && !isAdd">{{ sampleInfo.address }}</span>
                  <el-input v-model="sampleInfo.address" v-else />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template #title>
              <el-text class="form_sub_title">查看历史</el-text>
            </template>
            <el-table :data="viewList" :border="true">
              <el-table-column label="查看日期" prop="checkTime" />
              <el-table-column label="IP地址" prop="ip" />
              <el-table-column label="查看位置" prop="address" />
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" v-if="isEdit || isAdd" @click="submitForm">{{ $t(`global.verify`) }}</el-button>
        <el-button @click="cacel">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog>

    <el-dialog v-model="shareDialog" @closed="cacelShare" >
      <el-input v-model="shareLinks" />
      <el-row type="flex" justify="center" style="margin-top: 20px">
        <el-button type="primary" @click="copyLink">复制链接</el-button>
        <el-button @click="cacelShare">{{$t(`global.cancel`)}}</el-button>
      </el-row>
    </el-dialog>

  </ContentWrap>
</template>
<script lang="ts" setup>
import { FormInstance } from "element-plus";
import proList from '@/pages/hkb/components/proList/index.vue'
import * as sampleApi from '@/service/api/hkb/electronic/index'
import { ref } from 'vue'
import type {sampleVO, ColumnVO, ViewListVO} from '../types'
import { useRouter } from 'vue-router';
import axios from 'axios';
import {createView} from "@/service/api/hkb/view";
const router = useRouter()

// defineOptions({ name: 'Product' })

const showDetail = ref(false)
const showsampleDetail = ref(false)
const isAdd = ref(false) //是否新增
const isEdit = ref(false) //是否编辑
const childRef = ref()
const loading = ref(false) // 列表的加载中
const buttonLoading = ref(false) //按钮的加载
const total = ref(0) // 列表的总页数
const activeNames = ref('1')
const list = ref<sampleVO[]>([]) // 列表的数据
const viewList = ref<ViewListVO[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileDetailList = ref([]);
const accessDetail = ref(false)
const shareDialog = ref(false)
const shareLinks = ref('')
const message = useMessage() // 消息弹窗

const allCol = ref<ColumnVO[]>([
  { label: '样本名称', prop: 'name', width: '' },
  { label: '创建时间', prop: 'operTime', width: '200px' },
  { label: '有效期', prop: 'effectiveTime', width: '200px' },
  { label: '备注', prop: 'memo', width: '' },
  { label: '内部备注', prop: 'internalMemo', width: '' },
  { label: '样品列表', prop: 'list', width: '' },
  { label: '姓名', prop: 'username', width: '' },
  { label: '电话', prop: 'phone', width: '' },
  { label: '邮箱', prop: 'email', width: '' },
  { label: '公司地址', prop: 'address', width: '' },
  { label: '查看历史', prop: 'hislist', width: '' },
  { label: '创建人', prop: 'creator', width: '' }
])
const checkCol = ref<ColumnVO[]>([])
const checked = ref([])

const options = [
  {
    value: 'HTML',
    label: 'HTML',
  },
  {
    value: 'CSS',
    label: 'CSS',
  },
  {
    value: 'JavaScript',
    label: 'JavaScript',
  },
]

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
}) // 查询参数

const sampleFormRef = ref<FormInstance>()
const sampleInfo = ref<sampleVO>({
  id: '',
  name: '',
  operTime: '',
  memo: '',
  internalMemo: '',
  username: '',
  phone: '',
  email: '',
  address: '',
  effectiveTime: '',
  productids: '',
  list: [],//商品列表
})
const sampleInfoInitForm = ref<sampleVO>({
  id: '',
  name: '',
  operTime: '',
  memo: '',
  internalMemo: '',
  username: '',
  phone: '',
  email: '',
  address: '',
  effectiveTime: '',
  productids: '',
  list: [],
})

const singleView = ref<ViewListVO>({
  checkTime:'',
  ip:'',
  address: '',
  viewType: '',
  sampleid: '',
})

const getList = async () => {
  const res = await sampleApi.getList(queryParams.value)
  console.log(res)
  if (res.list.length > 0) {
    list.value = res.list
    total.value = res.total
  }
}

//提交接待
const submitForm = async () => {
  let ids = []
  sampleInfo.value.list?.map(item => {
    ids.push(item.id)
  })
  sampleInfo.value.list = []//清空商品列表保留商品id
  sampleInfo.value.productids = ids.join(';')
  sampleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (sampleInfo.value.id) {
        await sampleApi.editSample(sampleInfo.value).finally(() => (buttonLoading.value = false));
      } else {
        console.log(sampleInfo.value)
        await sampleApi.addSample(sampleInfo.value).finally(() => (buttonLoading.value = false));
      }
      showsampleDetail.value = false;
      await getList();
    }
  })
}

/** 分享链接 **/
const shareLink = () => {
  console.log(12312)
  shareDialog.value = true
  shareLinks.value = window.location.href + '?shareId=' + sampleInfo.value.id
  console.log(window)
}

/** 取消分享 **/
const cacelShare = () => {
  shareDialog.value = false
}

/** 复制链接 **/
const copyLink = () => {
  navigator.clipboard.writeText(shareLinks.value);
  message.success('链接已复制到剪切板')
}

/** 记录分享访问次数 **/
const countShare = async () => {
  let id = router.currentRoute.value.query.shareId
  if(id){
    try {
      const response = await axios.get?.('https://qifu-api.baidubce.com/ip/local/geo/v1/district');
      singleView.value.checkTime = new Date()
      singleView.value.ip = response.data.ip
      singleView.value.address = response.data.data.prov + response.data.data.city + response.data.data.district
      singleView.value.viewType = '1'
      singleView.value.sampleid = id
    } catch (error) {
      console.error('请求错误', error);
      return null;
    }
    console.log(singleView)
    const res = await createView(singleView.value)
    let sharedPro = list.value.find(item => item.id === parseFloat(id))
    sampleDetails(sharedPro)
  }
}

/** 删除 **/
const deletesample = async () => {
  try {
    // 二次确认
    await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
    // 提交执行
    sampleApi.deleteSample(sampleInfo.value.id).then((res) => {
      if (res) {
        message.success('删除成功')
      } else {
        message.warning('删除失败')
      }
    }).finally(() => (cacel(), getList()))
  } catch (error) { }
}

//详情
const sampleDetails = (row) => {
  isEdit.value = false
  viewList.value = row?.hislist
  viewList.value.map(item => {
    item.checkTime = new Date(item.checkTime).toLocaleString()
    return item
  })
  showsampleDetail.value = true
  sampleInfo.value = row
}

const editDetails = (row) => {
  isEdit.value = true
  isAdd.value = false
  showsampleDetail.value = true
  viewList.value = row?.hislist
  viewList.value.map(item => {
    item.checkTime = new Date(item.checkTime).toLocaleString()
    return item
  })
  sampleInfo.value = row
}

/** 查看商品详情 **/
const proDetails = (row) => {
  isEdit.value = false
  isAdd.value = false
  showDetail.value = true
  childRef.value.initFormValue(row)
}

//显示新增
const showAdd = async () => {
  isEdit.value = false
  isAdd.value = true
  showsampleDetail.value = true
}

const showAccess = () => {
  accessDetail.value = true
}

//关闭弹窗
const cacel = () => {
  showsampleDetail.value = false
  accessDetail.value = false
  sampleFormRef.value?.resetFields()
  fileDetailList.value = []
  sampleInfo.value = JSON.parse(JSON.stringify(sampleInfoInitForm.value))
}

/** 激活时 */
onActivated(() => {
  getList()
  countShare()
})

/** 初始化 **/
onMounted(async () => {
  await getList()
  await countShare()
  checkCol.value = JSON.parse(JSON.stringify(allCol.value))
  checked.value = JSON.parse(JSON.stringify(allCol.value.map((item) => item.label)))
})

</script>
<style lang="scss" scoped>
.tableOp {
  margin-bottom: 10px;
}

.tag {
  margin: 5px 5px;
}

.form_sub_title {
  font-weight: 600;
}
</style>
